package view;

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import alto_nivel.gals.SemanticoAltoNivel;

import control.ControleAltoNivel;
import control.ControleIterativo;
import control.NotificaTela;

public class Tela extends JFrame implements NotificaTela {

    private static final long serialVersionUID = 1L;

    private JButton btNovo;
    private JButton btAbrir;
    private JButton btSalvar;
    private JButton btCopiar;
    private JButton btColar;
    private JButton btRecortar;
    private JButton btCompilar;
    private JButton btCodigo;
    private JButton btLinguagem;
    private JLabel labelStatus;
    private JLabel labelCaminho;
    private JPanel jPanel1;
    private JPanel jPanel2;
    private JPanel jPanel3;
    private JScrollPane jScrollPane1;
    private JScrollPane jScrollPane2;
    private JTextArea txConsole;
    private JTextArea txEditor;

    private Boolean linguagem;
    private TipoLinguagem tipoLinguagem;

    private TelaSelecaoLinguagem telaLinguagem;

    private ControleAltoNivel controleAltoNivel = new ControleAltoNivel();
    private ControleIterativo controleIterativo = new ControleIterativo();

    private final String modificado = "Modificado";
    private final String naoModificado = "Arquivo não modificado";

    private Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();

    private String txEditorContent = "";
    private String nomePrograma = "";
    private String diretorioPrograma = "";

    private String result;

    public Tela() {

	controleAltoNivel.setListener(this);
	controleIterativo.setListener(this);

	setSize(800, 675);
	setLocationRelativeTo(null);
	setTitle("GERADOR DE CÓDIGO LIR");
	initComponents();
	setVisible(true);
	txEditor.requestFocus();
    }

    private void initComponents() {

	jPanel1 = new JPanel();
	jPanel2 = new JPanel();
	btNovo = new JButton();
	btAbrir = new JButton();
	btSalvar = new JButton();
	btCopiar = new JButton();
	btColar = new JButton();
	btRecortar = new JButton();
	btCompilar = new JButton();
	btCodigo = new JButton();
	btLinguagem = new JButton();
	jScrollPane2 = new JScrollPane();
	txEditor = new JTextArea();
	jPanel3 = new JPanel();
	jScrollPane1 = new JScrollPane();
	txConsole = new JTextArea();
	labelStatus = new JLabel();
	labelCaminho = new JLabel();

	setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

	jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
	jPanel1.setAutoscrolls(true);
	jPanel2.setAutoscrolls(true);

	btNovo.setBackground(new java.awt.Color(238, 238, 238));
	btNovo.setIcon(new ImageIcon("imagens/New.png")); // NOI18N
	btNovo.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Novo", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.BOTTOM));
	btNovo.setFocusPainted(false);
	btNovo.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
	btNovo.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
	btNovo.addActionListener(new java.awt.event.ActionListener() {

	    @Override
	    public void actionPerformed(java.awt.event.ActionEvent evt) {
		btNovoActionPerformed(evt);
	    }
	});

	btAbrir.setBackground(new java.awt.Color(238, 238, 238));
	btAbrir.setIcon(new ImageIcon("imagens/Open.png")); // NOI18N
	btAbrir.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Abrir", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.BOTTOM));
	btAbrir.setFocusPainted(false);
	btAbrir.addActionListener(new java.awt.event.ActionListener() {

	    @Override
	    public void actionPerformed(java.awt.event.ActionEvent evt) {
		btAbrirActionPerformed(evt);
	    }
	});

	btSalvar.setBackground(new java.awt.Color(238, 238, 238));
	btSalvar.setIcon(new ImageIcon("imagens/Save.png")); // NOI18N
	btSalvar.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Salvar", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.BOTTOM));
	btSalvar.setFocusPainted(false);
	btSalvar.addActionListener(new java.awt.event.ActionListener() {

	    @Override
	    public void actionPerformed(java.awt.event.ActionEvent evt) {
		btSalvarActionPerformed(evt);
	    }
	});

	btCopiar.setBackground(new java.awt.Color(238, 238, 238));
	btCopiar.setIcon(new ImageIcon("imagens/Copy.png")); // NOI18N
	btCopiar.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Copiar", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.BOTTOM));
	btCopiar.setFocusPainted(false);
	btCopiar.addActionListener(new java.awt.event.ActionListener() {

	    @Override
	    public void actionPerformed(java.awt.event.ActionEvent evt) {
		btCopiarActionPerformed(evt);
	    }
	});

	btColar.setBackground(new java.awt.Color(238, 238, 238));
	btColar.setIcon(new ImageIcon("imagens/Paste.png")); // NOI18N
	btColar.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Colar", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.BOTTOM));
	btColar.addActionListener(new java.awt.event.ActionListener() {

	    @Override
	    public void actionPerformed(java.awt.event.ActionEvent evt) {
		btColarActionPerformed(evt);
	    }
	});

	btRecortar.setBackground(new java.awt.Color(238, 238, 238));
	btRecortar.setIcon(new ImageIcon("imagens/Cut.png")); // NOI18N
	btRecortar.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Recortar", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.BOTTOM));
	btRecortar.setFocusPainted(false);
	btRecortar.addActionListener(new java.awt.event.ActionListener() {

	    @Override
	    public void actionPerformed(java.awt.event.ActionEvent evt) {
		btRecortarActionPerformed(evt);
	    }
	});

	btCompilar.setBackground(new java.awt.Color(238, 238, 238));
	btCompilar.setIcon(new ImageIcon("imagens/Compile.png")); // NOI18N
	btCompilar.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Compilar", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.BOTTOM));
	btCompilar.setFocusPainted(false);
	btCompilar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
	btCompilar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
	btCompilar.addActionListener(new java.awt.event.ActionListener() {

	    @Override
	    public void actionPerformed(java.awt.event.ActionEvent evt) {

		btCompilarActionPerformed(evt);

	    }
	});

	btCodigo.setBackground(new java.awt.Color(238, 238, 238));
	btCodigo.setIcon(new ImageIcon("imagens/Code.png")); // NOI18N
	btCodigo.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Gerar Código", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.BOTTOM));
	btCodigo.setFocusPainted(false);
	btCodigo.addActionListener(new java.awt.event.ActionListener() {

	    @Override
	    public void actionPerformed(java.awt.event.ActionEvent evt) {
		btCodigoActionPerformed(evt);
	    }
	});

	btLinguagem.setBackground(new java.awt.Color(238, 238, 238));
	btLinguagem.setIcon(new ImageIcon("imagens/Team.PNG")); // NOI18N
	btLinguagem.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Linguagem", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.BOTTOM));
	btLinguagem.setFocusPainted(false);
	btLinguagem.addActionListener(new java.awt.event.ActionListener() {

	    @Override
	    public void actionPerformed(java.awt.event.ActionEvent evt) {
		btLinguagemActionPerformed(evt);
	    }
	});

	javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
	jPanel2.setLayout(jPanel2Layout);
	jPanel2Layout.setHorizontalGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	    .addGroup(
		      jPanel2Layout
			  .createSequentialGroup()
			  .addContainerGap()
			  .addGroup(
				    jPanel2Layout
					.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
					.addComponent(btLinguagem, javax.swing.GroupLayout.Alignment.LEADING,
						      javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
					.addComponent(btNovo, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE,
						      javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
					.addComponent(btAbrir, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE,
						      javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
					.addComponent(btSalvar, javax.swing.GroupLayout.Alignment.LEADING,
						      javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
					.addComponent(btCopiar, javax.swing.GroupLayout.Alignment.LEADING,
						      javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
					.addComponent(btColar, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE,
						      javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
					.addComponent(btRecortar, javax.swing.GroupLayout.Alignment.LEADING,
						      javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
						      Short.MAX_VALUE)
					.addComponent(btCompilar, javax.swing.GroupLayout.Alignment.LEADING,
						      javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
						      Short.MAX_VALUE)
					.addComponent(btCodigo, javax.swing.GroupLayout.Alignment.LEADING,
						      javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE))
			  .addContainerGap()));
	jPanel2Layout.setVerticalGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	    .addGroup(
		      jPanel2Layout.createSequentialGroup()
			  .addComponent(btNovo, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
			  .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
			  .addComponent(btAbrir, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
			  .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
			  .addComponent(btSalvar, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
			  .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
			  .addComponent(btCopiar, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
			  .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
			  .addComponent(btColar, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
			  .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
			  .addComponent(btRecortar, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
			  .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
			  .addComponent(btCompilar, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
			  .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
			  .addComponent(btCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
			  .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
			  .addComponent(btLinguagem, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
			  .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));

	txEditor.setColumns(20);
	txEditor.setRows(5);
	txEditor.setBorder(new NumberedBorder());
	jScrollPane2.setViewportView(txEditor);

	javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
	jPanel1.setLayout(jPanel1Layout);
	jPanel1Layout.setHorizontalGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	    .addGroup(
		      jPanel1Layout.createSequentialGroup()
			  .addContainerGap()
			  .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
					javax.swing.GroupLayout.PREFERRED_SIZE)
			  .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
			  .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 607, Short.MAX_VALUE)
			  .addContainerGap()));
	jPanel1Layout.setVerticalGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	    .addGroup(
		      jPanel1Layout
			  .createSequentialGroup()
			  .addContainerGap()
			  .addGroup(
				    jPanel1Layout
					.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
					.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 490, Short.MAX_VALUE)
					.addGroup(
						  jPanel1Layout.createSequentialGroup()
						      .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
								    javax.swing.GroupLayout.PREFERRED_SIZE)
						      .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))));

	jScrollPane1.setAutoscrolls(true);

	txConsole.setColumns(20);
	txConsole.setEditable(true);
	txConsole.setRows(3);
	jScrollPane1.setViewportView(txConsole);

	labelStatus.setText(naoModificado);

	labelCaminho.setText("");

	javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
	jPanel3.setLayout(jPanel3Layout);
	jPanel3Layout.setHorizontalGroup(jPanel3Layout
	    .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 780, Short.MAX_VALUE)
	    .addGroup(
		      jPanel3Layout.createSequentialGroup()
			  .addContainerGap()
			  .addComponent(labelStatus)
			  .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 688, Short.MAX_VALUE)
			  .addComponent(labelCaminho)
			  .addContainerGap()));
	jPanel3Layout.setVerticalGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	    .addGroup(
		      javax.swing.GroupLayout.Alignment.TRAILING,
		      jPanel3Layout.createSequentialGroup().addContainerGap().addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 74, Short.MAX_VALUE)
			  .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
			  .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(labelStatus).addComponent(labelCaminho))));

	javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
	getContentPane().setLayout(layout);
	layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	    .addGroup(
		      layout.createSequentialGroup()
			  .addContainerGap()
			  .addGroup(
				    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
					.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
					.addComponent(jPanel3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE,
						      javax.swing.GroupLayout.DEFAULT_SIZE,
						      Short.MAX_VALUE))
			  .addContainerGap()));
	layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
													       javax.swing.GroupLayout.Alignment.TRAILING,
													       layout
														   .createSequentialGroup()
														   .addContainerGap()
														   .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE,
																 javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
														   .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
														   .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE,
																 javax.swing.GroupLayout.DEFAULT_SIZE,
																 javax.swing.GroupLayout.PREFERRED_SIZE).addContainerGap()));

	setFocusable(true);

	jPanel1.setFocusable(false);
	jPanel2.setFocusable(false);
	jPanel3.setFocusable(false);
	txConsole.setFocusable(true);

	tecladoListener();
    }

    private void tecladoListener() {

	KeyAdapter ka = new KeyAdapter() {

	    @Override
	    public void keyPressed(KeyEvent e) {

		if (e.getKeyCode() == 78 && e.getModifiers() == 2) {
		    btNovo.doClick();

		} else if (e.getKeyCode() == 65 && e.getModifiers() == 2) {
		    btAbrir.doClick();

		} else if (e.getKeyCode() == 83 && e.getModifiers() == 2) {
		    btSalvar.doClick();

		} else if (e.getKeyCode() == 112) {
		    btLinguagem.doClick();

		} else if (e.getKeyCode() == 120) {
		    btCodigo.doClick();

		} else if (e.getKeyCode() == 119) {
		    btCompilar.doClick();

		}
	    }

	    @Override
	    public void keyReleased(KeyEvent e) {

		if (labelStatus.getText() == naoModificado) {
		    if (e.getSource().getClass() == JTextArea.class) {
			if (!txEditor.getText().equals(txEditorContent)) {
			    labelStatus.setText(modificado);
			}
		    }
		}
	    }
	};

	addKeyListener(ka);
	txEditor.addKeyListener(ka);
	txEditor.requestFocus();
    }

    private void btNovoActionPerformed(ActionEvent evt) {
	this.dispose();
	new Tela();
    }

    private void btAbrirActionPerformed(ActionEvent evt) {

	JFileChooser fileOpen = new JFileChooser();
	fileOpen.showOpenDialog(null);
	File file = fileOpen.getSelectedFile();

	try {

	    BufferedReader reader = new BufferedReader(new FileReader(file));
	    String linha;
	    txEditor.setText(null);

	    while ((linha = reader.readLine()) != null) {
		txEditor.append(linha + "\n");
	    }

	    reader.close();

	    labelStatus.setText(naoModificado);
	    labelCaminho.setText(file.getAbsolutePath());

	    txEditorContent = txEditor.getText();
	    diretorioPrograma = labelCaminho.getText();

	    nomePrograma = labelCaminho.getText();
	    nomePrograma = nomePrograma.substring(nomePrograma.lastIndexOf("\\") + 1, nomePrograma.length() - 4);

	} catch (Exception e) {
	    txConsole.setText(e.getMessage());
	}

	txEditor.requestFocus();
    }

    private void btSalvarActionPerformed(ActionEvent evt) {

	JFileChooser fc = new JFileChooser();

	fc.setSelectedFile(new File(labelCaminho.getText()));

	int result = fc.showSaveDialog(fc);

	File fFile = new File(".");

	if (result == JFileChooser.APPROVE_OPTION) {
	    fFile = fc.getSelectedFile();

	    if (fFile.exists()) {

		int response = JOptionPane.showConfirmDialog(null, "O arquivo já existe. Sobrescrever?", "Confirmar", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);

		if (response == JOptionPane.OK_OPTION) {
		    writeFile(fFile);
		}

	    } else {
		writeFile(fFile);
	    }
	}
    }

    private void writeFile(File fFile) {

	PrintWriter pw = null;

	String name = fFile.getName();
	String path = fFile.getAbsolutePath();
	if (name.lastIndexOf(".") == -1) {
	    fFile = new File(path += ".txt");
	}

	try {

	    pw = new PrintWriter(fFile);

	} catch (FileNotFoundException e) {
	    txConsole.setText("Arquivo não encontrado");
	}
	pw.print(txEditor.getText());
	pw.close();

	labelCaminho.setText(fFile.getAbsolutePath());
	labelStatus.setText(naoModificado);
	nomePrograma = labelCaminho.getText();
	nomePrograma = nomePrograma.substring(nomePrograma.lastIndexOf("\\") + 1, nomePrograma.length() - 4);
	diretorioPrograma = labelCaminho.getText();
	diretorioPrograma = diretorioPrograma.substring(0, diretorioPrograma.lastIndexOf("\\")) + "\\";

    }

    private void btCopiarActionPerformed(ActionEvent evt) {
	if (txEditor.getSelectedText() != null) {
	    StringSelection ss = new StringSelection(txEditor.getSelectedText());
	    clip.setContents(ss, ss);
	    txEditor.requestFocus();
	}
    }

    private void btColarActionPerformed(ActionEvent evt) {

	Transferable contents = clip.getContents(null);

	try {
	    result = (String) contents.getTransferData(DataFlavor.stringFlavor);

	    if (txEditor.getSelectedText() == null) {
		txEditor.insert(result, txEditor.getCaretPosition());

	    } else {
		txEditor.replaceSelection(result);
	    }

	    labelStatus.setText(modificado);
	    txEditor.requestFocus();

	} catch (UnsupportedFlavorException e) {
	    e.printStackTrace();

	} catch (IOException e) {
	    e.printStackTrace();
	}
    }

    private void btRecortarActionPerformed(ActionEvent evt) {
	if (txEditor.getSelectedText() != null) {
	    StringSelection ss = new StringSelection(txEditor.getSelectedText());
	    clip.setContents(ss, ss);
	    txEditor.replaceSelection(null);
	    labelStatus.setText(modificado);
	    txEditor.requestFocus();
	}
    }

    private void btCompilarActionPerformed(ActionEvent evt) {

	if (linguagem == null) {
	    JOptionPane.showConfirmDialog(null, "Selecione a linguagem de entrada!",
					  "Erro - Selecione a linguagem de entrada",
					  JOptionPane.OK_CANCEL_OPTION,
					  JOptionPane.QUESTION_MESSAGE);

	    btLinguagem.requestFocus();

	    return;

	} else if (TipoLinguagem.ALTO_NIVEL.equals(tipoLinguagem)) {

	    controleAltoNivel.setConteudo(txEditor.getText());
	    controleAltoNivel.analisar();

	    txEditor.requestFocus();

	} else if (TipoLinguagem.ITERATIVA.equals(tipoLinguagem)) {

	    controleIterativo.setConteudo(txEditor.getText());
	    controleIterativo.analisar();

	    txEditor.requestFocus();
	}

    }

    private void btCodigoActionPerformed(ActionEvent evt) {

	String nomePrograma = "";

	btCompilar.doClick();

	if (linguagem == null) {
	    return;
	}

	List<String> codigoMonolitico = new ArrayList<String>();
	String header = "";

	if (TipoLinguagem.ALTO_NIVEL.equals(tipoLinguagem)) {

	    codigoMonolitico = controleAltoNivel.gerarCodigo();
	    nomePrograma = controleAltoNivel.getNomePrograma();
	    header = controleAltoNivel.construirHeader();
	    codigoMonolitico.add(0, header);

	} else if (TipoLinguagem.ITERATIVA.equals(tipoLinguagem)) {
	    codigoMonolitico = controleIterativo.gerarCodigo();
	    nomePrograma = controleIterativo.getNomePrograma();	    
	}

	File arq = null;

	if (!diretorioPrograma.equals("")) {
	    String novoDir = diretorioPrograma.substring(0, diretorioPrograma.lastIndexOf("\\")) + "\\";
	    arq = new File(novoDir + nomePrograma + ".mon");

	} else {
	    arq = new File(nomePrograma + ".mon");
	}

	PrintWriter pw = null;

	try {
	    pw = new PrintWriter(arq);

	} catch (FileNotFoundException e) {
	    txConsole.setText("Falha ao criar arquivo de código monolítico");
	}
	for (String s : codigoMonolitico) {
	    pw.println(s);
	    txConsole.append(s + "\n");
	}
	pw.close();

	txEditor.requestFocus();
    }

    private void btLinguagemActionPerformed(ActionEvent evt) {
	if (telaLinguagem == null) {
	    telaLinguagem = new TelaSelecaoLinguagem(this);
	}
    }

    @Override
    public void limpaTxConsole() {
	txConsole.setText(null);
    }

    @Override
    public void saidaConsoleSucesso(String analise) {
	txConsole.append(analise + "\n");
    }

    @Override
    public void saidaConsoleErro(String analise) {
	txConsole.setText(analise);
    }

    public Boolean getLinguagem() {
	return linguagem;
    }

    public void setLinguagem(Boolean linguagem) {
	this.linguagem = linguagem;
    }

    public TipoLinguagem getTipoLinguagem() {
	return tipoLinguagem;
    }

    public void setTipoLinguagem(TipoLinguagem tipoLinguagem) {
	this.tipoLinguagem = tipoLinguagem;
    }

    public void setTelaLinguagem(TelaSelecaoLinguagem telaLinguagem) {
	this.telaLinguagem = telaLinguagem;
    }

    public static void main(String args[]) throws SQLException {	
	new Tela();
    }

}
